package com.ece.users;

import java.io.IOException;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ece.beans.items.Item;
import com.ece.beans.users.Utilisateur;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Context context = new InitialContext();
			UtilisateurBusinessControllerRemote ubc = (UtilisateurBusinessControllerRemote)context.lookup("UtilisateurBusinessController/remote");

			String email = request.getParameter("id");
			String pass = request.getParameter("pwd");
			if(email == null || "".equals(email) || pass == null || "".equals(pass))
				request.getRequestDispatcher("connexion.jsp").forward(request, response);
			else {
				Utilisateur user = ubc.login(email, pass);
				if(user == null)
					request.getRequestDispatcher("connexion.jsp").forward(request, response);
				else {
					request.getSession().setAttribute("connected",true);
					request.getSession().setAttribute("user", user);
					request.getSession().setAttribute("cart", new ArrayList<Item>());
					request.getRequestDispatcher("index.jsp").forward(request, response);
				}
			}

		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

}
